//
//  HomeViewController.m
//  YunGui
//
//  Created by wmm on 15/11/5.
//  Copyright © 2015年 hanen. All rights reserved.
//

#import "HomeViewController.h"
#import "VisitListCell2.h"
#import "VisitInfoViewController.h"
#import "VisitModel.h"
#import "SideMenuUtil.h"

#define LableHeight 20.0f
#define Height(msg) [UIView getHeight:msg]
#define Width(msg) [UIView getWidth:msg]

#pragma mark -
#pragma mark Constants

static CGFloat searchViewHight = 60.0f;

@interface HomeViewController (){

    float lastContentOffset;
    NSMutableArray *_dataArray;//tabledata
    int currentPage;
    int total;
    int currentNum;
    NSString *currentType;
    NSString *currentKeyword;
    NSArray *types;
    
    UIView *selectView;
    UIButton *righB;
}


@property (strong, nonatomic) UITableView *visitTableView;

@property (strong, nonatomic) UIView *topView;
@property (strong, nonatomic) UIView *searchView;
@property (strong, nonatomic) UITextField *searchFld;
@property (strong, nonatomic) UIButton *searchImgBtn;

@property (strong, nonatomic) UIButton *selectDayBtn;
@property (strong, nonatomic) UIButton *selectWeekBtn;
@property (strong, nonatomic) UIButton *selectMonBtn;
@property (strong, nonatomic) UIButton *selectAllBtn;

- (void)sideLeftButton_selector:(id)sender;

@end

@implementation HomeViewController

@synthesize revealController;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = GrayBackColor;
    
    self.view.frame = CGRectMake(0.0f, 0.0f, kScreenWidth, kScreenHeight);
    
    [SideMenuUtil addViewGesture:self revealController:revealController];
    
    //set NavigationBar 背景颜色&title 颜色
    [ViewTool setNavigationBar:self.navigationController.navigationBar];
    
    self.navigationItem.leftBarButtonItem=[ViewTool getListBarButtonItemWithTarget:self WithAction:@selector(sideLeftButton_selector:)];

    
    righB = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, Height(20), Height(20))];
    [righB setBackgroundImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
    [righB addTarget:self action:@selector(clickSearch:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barbtn = [[UIBarButtonItem alloc] initWithCustomView:righB];
    self.navigationItem.rightBarButtonItem = barbtn;
    
    self.navigationItem.title = @"我的拜访";
    
    [self drawTableView];
    [self drawTopView:self.view];
    [self drawAddBtn];
    
    _dataArray = [NSMutableArray array];
    currentPage = 1;//当前页数
    currentType = @"all";
    types = [NSArray arrayWithObjects:@"all",@"today",@"week",@"month", nil];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [_visitTableView deselectRowAtIndexPath:[_visitTableView indexPathForSelectedRow] animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)clickToNewVisit{

    AddVisitViewController *newVisitViewController = [[AddVisitViewController alloc] init];
    newVisitViewController.delegate = self;
    [self.navigationController pushViewController:newVisitViewController animated:YES];
}

- (void)drawAddBtn{
    UIButton *button = [ViewTool getAddButtonWithTarget:self WithString:@"add.png" WithAction:@selector(clickToNewVisit)];
    [self.view addSubview:button];
    [self.view bringSubviewToFront:button];
}

- (void)initData:(NSString *)type keyword:(NSString *)keyword page:(int)page pageNum:(int)pageNum success:(SuccessBlock)successBlock fail:(FailBlock)faileBlock{

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:@"app.visit.my.visit" forKey:@"method"];
    [dictionary setObject:type forKey:@"type"];
    [dictionary setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] forKey:@"user_id"];

    if (keyword != nil & keyword.length != 0) {
        [dictionary setObject:keyword forKey:@"search"];
    }

    [dictionary setObject:[NSNumber numberWithInt:page] forKey:@"page"];
    [dictionary setObject:[NSNumber numberWithInt:pageNum] forKey:@"pageNum"];
    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dictionary] success:^(id data) {

        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *status = [(NSDictionary *)jsonDic objectForKey:@"status"];
        if ([status isEqualToString:@"SUCCESS"]) {
            NSDictionary * dataDict = [DataTool changeType:[(NSDictionary *)jsonDic objectForKey:@"data"]];
            total = [[dataDict objectForKey:@"total"] intValue];
            NSMutableArray *visitArray = [dataDict objectForKey:@"listData"];
            currentNum = (int)visitArray.count;
            for (int i=0; i<visitArray.count; i++) {
                VisitModel *model = [[VisitModel alloc] init];
                [model setValuesForKeysWithDictionary:visitArray[i]];
                [_dataArray addObject:model];
            }
            if (total <= 10) {
                [_visitTableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                if (currentNum < 10) {
                    [_visitTableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                   [_visitTableView.mj_footer endRefreshing];
                }
            }
        }else{
            currentNum = 0;
            int code = [[(NSDictionary *)jsonDic objectForKey:@"code"] intValue];
            NSString *msg = [(NSDictionary *)jsonDic objectForKey:@"msg"];
            [Tools showMessage:msg view:self];
            if (code == 999991) {
                [_dataArray removeAllObjects];
                [_visitTableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        [_visitTableView reloadData];
        successBlock(status);
    } fail:^(NSError *error) {

        [Tools showMessage:error.localizedDescription view:self];
        [_visitTableView.mj_footer endRefreshingWithNoMoreData];
        faileBlock(error);
    }];
}

- (void)showSearchView{
    
    if (_topView.hidden) {
        _topView.hidden = NO;
        _visitTableView.userInteractionEnabled = YES;
        selectView.frame = CGRectMake(0.0f, searchViewHight, kScreenWidth, searchViewHight);
        
    }else{
        [_searchFld setText:@""];
        [_searchFld resignFirstResponder];
        _topView.hidden = YES;
        _visitTableView.userInteractionEnabled = YES;
        selectView.frame = CGRectMake(0.0f, 0, kScreenWidth, searchViewHight);
        
    }
}
- (void)clickSearch:(UIButton *)btn
{
    
        if (btn.selected == NO) {
            _topView.hidden = NO;
            selectView.frame = CGRectMake(0,  _topView.height, kScreenWidth, 60.0f);
            _visitTableView.frame = CGRectMake(0, selectView.height + 15 + _topView.height, kScreenWidth,kScreenHeight - selectView.height - 15 -_topView.height -64);
            
        }else{
           _searchFld.text = @"";
            _topView.hidden = YES;
            selectView.frame = CGRectMake(0, 0, kScreenWidth, 60.0f);
            _visitTableView.frame = CGRectMake(0, selectView.height + 15, kScreenWidth, kScreenHeight - selectView.height - 15 -64);
          
        }
        btn.selected = !btn.selected;
    
    
}

- (UIButton *)getSelectButtonWithFrame:(CGRect)frame withTitle:(NSString *)title {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button setTitleColor:UIColorFromRGB(0xa5aab0) forState:UIControlStateNormal];
    button.titleLabel.font= [ViewTool getFont:15.0f];
    return button;
}

//商务经理
-(void)drawTopView:(UIView *)subView
{
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, searchViewHight)];
    [self.view addSubview:_topView];
    
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, searchViewHight)];
    [searchView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"Btn_Normal_Sousuodi.png"]]];

    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, self.view.width-40, searchView.height-20)];
    imgView.image = [UIImage imageNamed:@"Btn_Normal_Sousuokuang.png"];
    
    _searchFld = [[UITextField alloc] initWithFrame:CGRectMake(imgView.x+10,imgView.y,imgView.width,imgView.height)];
    _searchFld.placeholder = @"时间/小区名称/网点编号";
    _searchFld.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _searchFld.returnKeyType = UIReturnKeySearch;

    [_searchFld setValue:LEFTLINECOLOR forKeyPath:@"_placeholderLabel.textColor"];
    [_searchFld setValue:[UIFont systemFontOfSize:16.0f] forKeyPath:@"_placeholderLabel.font"];

    _searchFld.returnKeyType = UIReturnKeySearch;
    _searchFld.delegate = self;
    
    [searchView addSubview:imgView];
    [searchView addSubview:_searchFld];
    [searchView addSubview:_searchImgBtn];

    [_topView addSubview:searchView];

    _topView.hidden = YES;
}

- (void)stopUseBtn{
    _selectDayBtn.userInteractionEnabled = NO;
    _selectWeekBtn.userInteractionEnabled = NO;
    _selectMonBtn.userInteractionEnabled = NO;
    _selectAllBtn.userInteractionEnabled = NO;
}

- (void)startUseBtn{
    _selectDayBtn.userInteractionEnabled = YES;
    _selectWeekBtn.userInteractionEnabled = YES;
    _selectMonBtn.userInteractionEnabled = YES;
    _selectAllBtn.userInteractionEnabled = YES;
}

- (void)reloadVisitData:(UIButton *)button{
    
    [_selectDayBtn setTitleColor:UIColorFromRGB(0xa5aab0) forState:UIControlStateNormal];
    [_selectWeekBtn setTitleColor:UIColorFromRGB(0xa5aab0) forState:UIControlStateNormal];
    [_selectMonBtn setTitleColor:UIColorFromRGB(0xa5aab0) forState:UIControlStateNormal];
    [_selectAllBtn setTitleColor:UIColorFromRGB(0xa5aab0) forState:UIControlStateNormal];
    [_selectDayBtn setBackgroundImage:nil forState:UIControlStateNormal];
    [_selectWeekBtn setBackgroundImage:nil forState:UIControlStateNormal];
    [_selectMonBtn setBackgroundImage:nil forState:UIControlStateNormal];
    [_selectAllBtn setBackgroundImage:nil forState:UIControlStateNormal];
    
    [button setTitleColor:UIColorFromRGB(0xff7703) forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"Btn_Normal_Yishenpi"] forState:UIControlStateNormal];
    [SVProgressHUD showWithStatus:@"加载中"];
    [self stopUseBtn];
    
    [_dataArray removeAllObjects];
    currentKeyword = _searchFld.text;
    currentType = types[button.tag];
    currentPage = 1;
    [self initData:currentType keyword:currentKeyword page:currentPage pageNum:10 success:^(id data) {
        [SVProgressHUD dismiss];
        [self startUseBtn];
    } fail:^(NSError *error) {
        [SVProgressHUD dismiss];
        [self startUseBtn];
    }];
}

-(void)drawTableView
{
    selectView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, kScreenWidth, searchViewHight)];
    selectView.backgroundColor = [UIColor whiteColor];
    
    _selectAllBtn = [self getSelectButtonWithFrame:CGRectMake(20, 5, (kScreenWidth-40)/4, searchViewHight-10) withTitle:@"全部"];
    _selectAllBtn.tag = 0;
    [_selectAllBtn setTitleColor:UIColorFromRGB(0xff7703) forState:UIControlStateNormal];
    [_selectAllBtn setBackgroundImage:[UIImage imageNamed:@"Btn_Normal_Yishenpi"] forState:UIControlStateNormal];
    [_selectAllBtn addTarget:self action:@selector(reloadVisitData:) forControlEvents:UIControlEventTouchUpInside];
    
    _selectDayBtn = [self getSelectButtonWithFrame:CGRectMake(_selectAllBtn.maxX, _selectAllBtn.y, _selectAllBtn.width, _selectAllBtn.height) withTitle:@"当日"];
    _selectDayBtn.tag = 1;
    [_selectDayBtn addTarget:self action:@selector(reloadVisitData:) forControlEvents:UIControlEventTouchUpInside];
    
    _selectWeekBtn = [self getSelectButtonWithFrame:CGRectMake(_selectDayBtn.maxX, _selectAllBtn.y, _selectAllBtn.width, _selectAllBtn.height) withTitle:@"本周"];
    _selectWeekBtn.tag = 2;
    [_selectWeekBtn addTarget:self action:@selector(reloadVisitData:) forControlEvents:UIControlEventTouchUpInside];
    
    _selectMonBtn = [self getSelectButtonWithFrame:CGRectMake(_selectWeekBtn.maxX, _selectAllBtn.y, _selectAllBtn.width, _selectAllBtn.height) withTitle:@"本月"];
    _selectMonBtn.tag = 3;
    [_selectMonBtn addTarget:self action:@selector(reloadVisitData:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:selectView];
    [selectView addSubview:_selectAllBtn];
    [selectView addSubview:_selectDayBtn];
    [selectView addSubview:_selectWeekBtn];
    [selectView addSubview:_selectMonBtn];
    
    
    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(0, selectView.maxY - 1, kScreenWidth, 1)];
    lineView1.backgroundColor = UIColorFromRGB(0xe8e7ec);
    [selectView addSubview:lineView1];
    
    CGFloat grayH = 15;
    
    UIView *sectionView = [ViewTool getLineViewWith:CGRectMake(0, selectView.maxY, kScreenWidth, grayH) withBackgroudColor:GrayBackColor];
    [selectView addSubview:sectionView];
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, sectionView.maxY - 1, kScreenWidth, 1)];
    lineView.backgroundColor = UIColorFromRGB(0xe8e7ec);
    [selectView addSubview:lineView];
    
    _visitTableView=[[UITableView alloc]initWithFrame:CGRectMake(0.0f, lineView.maxY, kScreenWidth, kScreenHeight-64-lineView.maxY) style:UITableViewStylePlain];
    _visitTableView.delegate=self;
    _visitTableView.dataSource=self;
    _visitTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    _visitTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    // 马上进入刷新状态
    [_visitTableView.mj_header beginRefreshing];
    
    _visitTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadMoreData];
        });
    }];
    [self.view addSubview:_visitTableView];
}

#pragma mark - 数据处理相关
#pragma mark 下拉刷新数据
- (void)loadNewData
{
    currentPage = 1;
    [_dataArray removeAllObjects];
    currentKeyword = _searchFld.text;
    [self initData:currentType keyword:currentKeyword page:currentPage pageNum:10 success:^(id data) {
        [_visitTableView.mj_header endRefreshing];
    } fail:^(NSError *error) {
        [_visitTableView.mj_header endRefreshing];
    } ];
    
}

#pragma mark 上拉加载更多数据
- (void)loadMoreData
{
    currentPage++;
    currentKeyword = _searchFld.text;
    [self initData:currentType keyword:currentKeyword page:currentPage pageNum:10 success:^(id data) {
        
    } fail:^(NSError *error) {

    }];
    // 拿到当前的下拉刷新控件，结束刷新状态
}

#pragma mark - UITableViewDataSource数据源方法
#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

#pragma mark返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //NSIndexPath是一个对象，记录了组和行信息
    static NSString *CellIdentifier = @"VisitListCell";
    VisitListCell2 *cell = (VisitListCell2 *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[VisitListCell2 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    if (_dataArray.count >0) {
        
        VisitModel *model = _dataArray[indexPath.row];
        cell.visitNum.text=model.branch_no;
        cell.visitSub.text=[NSString stringWithFormat:@"小区:%@",model.complex];
        cell.visitPro.text=[NSString stringWithFormat:@"物业:%@",model.property];
        cell.visitDate.text=model.last_at;
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 95.0f;
}

/// 处理单元格点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    VisitInfoViewController *visitDetailVC=[[VisitInfoViewController alloc]init];
    visitDetailVC.model = _dataArray[indexPath.row];
    visitDetailVC.delegate = self;
    [self.navigationController pushViewController:visitDetailVC animated:NO];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    lastContentOffset = scrollView.contentOffset.y;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    
    if (lastContentOffset < scrollView.contentOffset.y) {
        NSLog(@"向上滚动");
    }else{
        NSLog(@"向下滚动");
    }
}

#pragma mark textfield 搜索
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == _searchFld) {
        [theTextField resignFirstResponder];
    }
    [self search];
    return YES;
}

- (void)search{
    
    if (_searchFld.text == nil || _searchFld.text.length == 0) {
        [Tools showMessage:@"请输入搜索关键字" view:self];
        return;
    }
    [_searchFld resignFirstResponder];
    currentPage = 1;
    [_dataArray removeAllObjects];
    [SVProgressHUD showWithStatus:@"搜索中"];
    currentKeyword = _searchFld.text;
    [self initData:currentType keyword:currentKeyword page:currentPage pageNum:10 success:^(id data) {
        [SVProgressHUD dismiss];

    } fail:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
}

// 拉开左侧:点击.
- (void)sideLeftButton_selector:(id)sender {
    
    [self.revealController toggleSidebar:!self.revealController.sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
}

//AddVisitViewController@protocol UIViewPassValueDelegate
- (void)passValue:(NSString *)value{
    NSLog(@"HOMEVC_passValue:%@",value);
    if ([value isEqualToString:@"SUCCESS"]) {
        [_visitTableView.mj_header beginRefreshing];
    }
}

@end
